#include "Random.h"

#define Printf Printf0
#define Print Print0
#define Println Println0
#define Printfln Printfln0

void Random_Init()
{ 
  rcu_periph_clock_enable(RCU_TRNG); 
  trng_deinit();
  trng_enable(); 
}

/*!
    \brief      check whether the TRNG module is ready
    \param[in]  none
    \param[out] none
    \retval     ErrStatus: SUCCESS or ERROR
*/
ErrStatus trng_ready_check(void)
{
    uint32_t timeout = 0;
    FlagStatus trng_flag = RESET;
    ErrStatus reval = SUCCESS;
    
    /* check wherther the random data is valid */
    do{
        timeout++;
        trng_flag = trng_flag_get(TRNG_FLAG_DRDY);
    }while((RESET == trng_flag) &&(0xFFFF > timeout));
    
    if(RESET == trng_flag)
    {   
        /* ready check timeout */
        // printf("Error: TRNG can't ready \r\n");
        // trng_flag = trng_flag_get(TRNG_FLAG_CECS);
        // printf("Clock error current status: %d \r\n", trng_flag);
        // trng_flag = trng_flag_get(TRNG_FLAG_SECS);
        // printf("Seed error current status: %d \r\n", trng_flag);  
        // reval = ERROR;
    }
    
    /* return check status */
    return reval;
}

/*!
    \brief      get random data in range
    \param[in]  none
    \param[out] none
    \retval     random data
*/
int Random(int min, int max)
{
  if (SUCCESS == trng_ready_check())
  {
    return (trng_get_true_random_data() % (max - min + 1) + min);
  }
  else
  {
    return 0;
  }
}
